package com.fireXXX.job.analysis.crawler.boss.progress;

import com.fireXXX.job.analysis.crawler.boss.constant.CityTypeEnum;
import com.fireXXX.job.analysis.crawler.boss.constant.EmployeeNumberTypeEnum;
import com.fireXXX.job.analysis.crawler.boss.constant.IndustryTypeEnum;
import com.fireXXX.job.analysis.crawler.boss.constant.PublicStepTypeEnum;
import com.fireXXX.job.analysis.crawler.util.FileUtil;
import com.fireXXX.job.analysis.crawler.util.JacksonUtil;
import lombok.Getter;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Map;

@Component
public class CompanyProgressManager {

    @Getter
    private static CompanyProgress companyProgress;

    private static String path = null;

    private static String failPath = null;

    static {
        try {
            path = new File("").getCanonicalPath() + "/crawler/src/main/resources/company_progress.txt";
            failPath = new File("").getCanonicalPath() + "/crawler/src/main/resources/company_fail.txt";
        } catch (IOException e) {
            e.printStackTrace();
        }

        String content = null;
        try {
            content = new String(
                    Files.readAllBytes(
                            new File(path).toPath()
                    )
            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, Object> map = null;
        try {
            map = JacksonUtil.toObject(content, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        CityTypeEnum cityTypeEnum = CityTypeEnum.valueOf(map.get("city").toString());
        IndustryTypeEnum industryTypeEnum = IndustryTypeEnum.valueOf(map.get("industry").toString());
        PublicStepTypeEnum publicStepTypeEnum = PublicStepTypeEnum.valueOf(map.get("publicStep").toString());
        EmployeeNumberTypeEnum employeeNumberTypeEnum = EmployeeNumberTypeEnum.valueOf(map.get("employeeNumber").toString());
        int page = (int) map.get("page");
        companyProgress = new CompanyProgress(cityTypeEnum, industryTypeEnum, publicStepTypeEnum, employeeNumberTypeEnum, page);
    }

    public void updateProgress(CompanyProgress companyProgress) {
        this.companyProgress = companyProgress;
        try {
            FileUtil.writeToFile(path, JacksonUtil.toJsonStringSafe(companyProgress));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void signFail(CompanyProgress companyProgress) {
        try {
            FileUtil.appendLineToFie(failPath, JacksonUtil.toJsonStringSafe(companyProgress));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
